package com.xckj.zuoliao.framework;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.gyf.immersionbar.ImmersionBar;
import com.xckj.zuoliao.R;
import com.xckj.zuoliao.view.LoadingDialog;

/**
 * @Author: 代码的搬运工
 * @Describe: Activity的基类
 * @Date: 2024/3/26 23:49
 */
public abstract class BaseActivity<T extends ViewDataBinding> extends AppCompatActivity implements IBaseView {
    protected T dataBinding;
    private ImmersionBar mImmersionBar;
    private LoadingDialog loadingDialog;
    private Activity activity;
    private int dialogCount = 0;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(loadLayout());
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        activity = this;
        dataBinding = DataBindingUtil.setContentView(this, loadLayout());
        initData();
        setListener();
        initStatusBar();
    }

    /**
     * 加载布局
     *
     * @return 布局Id
     */
    abstract protected int loadLayout();

    /**
     * 初始化数据
     */
    abstract protected void initData();

    /**
     * 设置监听
     */
    abstract protected void setListener();

    /**
     * 初始化沉浸式状态栏
     */
    private void initStatusBar() {
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init();
        }
    }

    /**
     * 是否使用沉浸式状态栏
     *
     * @return true or false
     */
    protected boolean isStatusBarEnabled() {
        return true;
    }

    /**
     * 状态栏字体是否深色模式
     *
     * @return true or false
     */
    protected boolean isStatusBarDarkFont() {
        return true;
    }

    protected boolean isFitsSystemWindows() {
        return true;
    }

    /**
     * 设置状态栏颜色
     */
    protected int setStatusBarColor() {
        return R.color.status_bar_red;
    }

    /**
     * 初始化沉浸式状态栏
     *
     * @return ImmersionBar
     */
    @SuppressLint("ResourceType")
    protected ImmersionBar createStatusBarConfig() {
        return ImmersionBar
                .with(this)
                .fitsSystemWindows(isFitsSystemWindows())
                .statusBarDarkFont(isStatusBarDarkFont())
                .statusBarColor(setStatusBarColor())
                .keyboardEnable(false)
                .navigationBarColor(R.color.white)
                .autoDarkModeEnable(true)
                .autoNavigationBarDarkModeEnable(true);
    }

    /**
     * 获取状态栏沉浸的配置对象
     *
     * @return ImmersionBar
     */
    public ImmersionBar getStatusBarConfig() {
        if (null == mImmersionBar) {
            mImmersionBar = createStatusBarConfig();
        }
        return mImmersionBar;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            hideKeyboard(ev, view, BaseActivity.this);
        }
        return super.dispatchTouchEvent(ev);

    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard(MotionEvent event, View view, Activity activity) {
        try {
            if (view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left + view.getWidth(), bootom = top + view.getHeight();
                // （判断是不是EditText获得焦点）判断焦点位置坐标是否在控件所在区域内，如果位置在控件区域外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示Loading
     */
    @Override
    public void showLoading() {
        runOnUiThread(() -> {
            dialogCount++;
            if (null == loadingDialog || !loadingDialog.isShowing()) {
                loadingDialog = new LoadingDialog(this);
                loadingDialog.create();
            }
            if (!loadingDialog.isShowing()) {
                loadingDialog.show();
            }
        });
    }

    /**
     * 隐藏Loading
     */
    @Override
    public void hideLoading() {
        runOnUiThread(() -> {
            dialogCount--;
            if (null == loadingDialog) {
                return;
            }
            if (dialogCount <= 0) {
                loadingDialog.dismiss();
            }
        });
    }

    @Override
    public void showMsg(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            runOnUiThread(() -> Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }
}
